<!DOCTYPE html>
<html lang="en">
<head>
	<title>Virtual Document</title>
	<style id="_defaultStyles"></style>
</head>
<body style="margin: 0; overflow: hidden; width: 100%; height: 100%">
	<iframe id="_target" frameborder="0" style="margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%"></iframe>
	<script>
		'use strict';

		const ipcRenderer = require('electron').ipcRenderer;
		const target = document.getElementById('_target');

		let initData = {};

		ipcRenderer.on('baseUrl', function(event, value) {
			initData.baseUrl = value;
		});

		ipcRenderer.on('styles', function(event, value) {
			initData.styles = value;

			// webview
			let defaultStyles = document.getElementById('_defaultStyles');
			defaultStyles.innerHTML = value;

			// iframe
			defaultStyles = target.contentDocument.getElementById('_defaultStyles');
			if(defaultStyles) {
				defaultStyles.innerHTML = value;
			}
		});

		// propagate focus
		ipcRenderer.on('focus', function() {
			target.contentWindow.focus();
		});

		// update iframe-contents
		ipcRenderer.on('content', function(event, value) {

			const parser = new DOMParser();
			const newDocument = parser.parseFromString(value.join('\n'), 'text/html');

			// set base-url if possible
			if(initData.baseUrl) {
				const baseElement = document.createElement('base');
				baseElement.href = initData.baseUrl;
				newDocument.head.appendChild(baseElement);
			}

			// apply default styles
			const defaultStyles = newDocument.createElement('style');
			defaultStyles.id = '_defaultStyles';
			defaultStyles.innerHTML = initData.styles;
			if (newDocument.head.hasChildNodes()) {
				newDocument.head.insertBefore(defaultStyles, newDocument.head.firstChild);
			} else {
				newDocument.head.appendChild(defaultStyles);
			}

			// script to bubble out link-clicks
			const defaultScripts = newDocument.createElement('script');
			defaultScripts.innerHTML = `
				document.body.addEventListener('click', function(event) {
					let node = event.target;
					while (node) {
						if (node.tagName === 'A' && node.href && node.href[0] !== '#') {
							window.parent.postMessage({ command: 'did-click-link', data: node.href }, 'file://');
							event.preventDefault();
							break;
						}
						node = node.parentNode;
					}
				});`
			newDocument.body.appendChild(defaultScripts);

			// write new content onto iframe
			target.contentDocument.open('text/html', 'replace');
			target.contentDocument.write(newDocument.documentElement.innerHTML);
			target.contentDocument.close();

		});

		// forward messages from the embedded iframe
		window.onmessage = function(message) {
			const { command, data} = message.data;
			ipcRenderer.sendToHost(command, data);
		};

		// signal ready
		ipcRenderer.sendToHost('webview-ready', process.pid);
	</script>
</body>
</html>